using System.Collections.Generic;
using SqlQueryBuilder.Clauses;
using SqlQueryBuilder.Util;

namespace SqlQueryBuilder.Criterias
{
    /// <summary>
    /// Group by Criteria
    /// </summary>
    public class GroupBy : ICriteria
    {
        /// <summary>
        /// Gets or sets the group by clauses.
        /// </summary>
        /// <value>The group by clauses.</value>
        public List<GroupByClause> GroupByClauses { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="GroupBy"/> class.
        /// </summary>
        public GroupBy()
        {
            GroupByClauses = new List<GroupByClause>();
        }

        /// <summary>
        /// Builds the criteria.
        /// </summary>
        /// <returns></returns>
        public string BuildCriteria()
        {
            if (GroupByClauses.Count == 0) return string.Empty;

            bool firstClause = true;
            string groupBy = string.Empty;
            foreach (var groupByClause in GroupByClauses)
            {
                if (firstClause)
                    firstClause = false;
                else
                    groupBy = SqlMultipleFields.AddSeparator(groupBy);

                groupBy += string.Format("{0} ", groupByClause.groupByClause);
            }
            return string.Format("GROUP BY {0}",groupBy);
        }
    }
}